from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from .models import Area
from .serializers import AreaSerializers, SubAreaSerializers
# Create your views here.


class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """省市区三级联动视图"""
    # 不进行分页
    pagination_class = None

    # 1.获取查询集
    def get_queryset(self):
        # 判断请求行为
        if self.action == 'list':
            # parent为None的为省份
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    # 2.获取序列化器类
    def get_serializer_class(self):
        # 判断请求行为
        if self.action == 'list':
            return AreaSerializers
        else:
            return SubAreaSerializers
